/* eslint-disable */
import {login, getInfo} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    id: ''
  }
}

const state = getDefaultState()

const mutations = {
  // SETT_USER: (state, user) => {
  //   state.token = user.token
  //   state.name = user.name
  //   state.avatar = user.avatar
  // },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    // 将token存入网页缓存
    setToken(token)
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERID: (state, id) => {
    state.id = id
  }
}

const actions = {
  // 用户登录
  async login({commit}, userInfo) {
    // 登录后端
    const data = await login(userInfo);
    console.log(data)
    commit('SET_TOKEN', data.token)
  },

  // get user info
  async getInfo({commit, state}) {
    const response = await getInfo(state.token)
    console.log("获取用户信息：", response)
    if (!response) {
      return reject('Verification failed, please Login again.')
    }
    const name = response.username
    const avatar = response.img_url
    const id = response.id
    commit('SET_NAME', name)
    commit('SET_AVATAR', avatar)
    commit('SET_USERID', id)
  },

// user logout
  logout({commit}) {
    removeToken()
    // resetRouter()
    commit('RESET_STATE')
  },

// remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,//开启命名空间
  state,
  mutations,
  actions
}

